package com.djf.djfcs.listener;

import com.alibaba.fastjson.JSON;
import com.djf.djfcs.canal.CanalDataChangeEvent;
import com.djf.djfcs.canal.CanalDataListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 用户配送表Canal数据监听器
 */
@Slf4j
@Component
public class UserDeliveryCanalListener implements CanalDataListener {
    
    @Override
    public void onDataChange(CanalDataChangeEvent event) {
        // 只处理用户配送表的变更
        if (!event.getTable().startsWith("user_delivery_")) {
            return;
        }
        
        log.info("用户配送表数据变更事件: {}.{}, 事件类型: {}", 
                event.getDatabase(), event.getTable(), event.getEventType());
        
        switch (event.getEventType()) {
            case "INSERT":
                handleInsert(event);
                break;
            case "UPDATE":
                handleUpdate(event);
                break;
            case "DELETE":
                handleDelete(event);
                break;
            default:
                log.warn("未知的事件类型: {}", event.getEventType());
        }
    }
    
    /**
     * 处理插入事件
     */
    private void handleInsert(CanalDataChangeEvent event) {
        if (event.getNewData() != null && !event.getNewData().isEmpty()) {
            for (Map<String, Object> row : event.getNewData()) {
                log.info("新增用户配送数据: {}", JSON.toJSONString(row));
                
                // 业务逻辑处理
                processDeliveryData(row, "INSERT");
            }
        }
    }
    
    /**
     * 处理更新事件
     */
    private void handleUpdate(CanalDataChangeEvent event) {
        if (event.getNewData() != null && !event.getNewData().isEmpty()) {
            for (int i = 0; i < event.getNewData().size(); i++) {
                Map<String, Object> newRow = event.getNewData().get(i);
                Map<String, Object> oldRow = null;
                if (event.getOldData() != null && i < event.getOldData().size()) {
                    oldRow = event.getOldData().get(i);
                }
                
                log.info("更新用户配送数据 - 原数据: {}, 新数据: {}", 
                        oldRow != null ? JSON.toJSONString(oldRow) : "null",
                        JSON.toJSONString(newRow));
                
                processDeliveryData(newRow, "UPDATE");
            }
        }
    }
    
    /**
     * 处理删除事件
     */
    private void handleDelete(CanalDataChangeEvent event) {
        if (event.getOldData() != null && !event.getOldData().isEmpty()) {
            for (Map<String, Object> row : event.getOldData()) {
                log.info("删除用户配送数据: {}", JSON.toJSONString(row));
                
                processDeliveryData(row, "DELETE");
            }
        }
    }
    
    /**
     * 处理配送数据业务逻辑
     */
    private void processDeliveryData(Map<String, Object> data, String operation) {
        try {
            String deliveryId = (String) data.get("id");
            String userId = (String) data.get("user_id");
            String status = (String) data.get("status");
            
            log.debug("处理配送数据: deliveryId={}, userId={}, status={}, operation={}", 
                    deliveryId, userId, status, operation);
            
            // 根据不同操作类型执行相应的业务逻辑
            switch (operation) {
                case "INSERT":
                    // 新增配送记录时的处理逻辑
                    handleNewDelivery(deliveryId, userId, data);
                    break;
                case "UPDATE":
                    // 更新配送记录时的处理逻辑
                    handleUpdateDelivery(deliveryId, userId, status, data);
                    break;
                case "DELETE":
                    // 删除配送记录时的处理逻辑
                    handleDeleteDelivery(deliveryId, userId, data);
                    break;
            }
            
        } catch (Exception e) {
            log.error("处理配送数据业务逻辑时发生异常", e);
        }
    }
    
    /**
     * 处理新增配送记录
     */
    private void handleNewDelivery(String deliveryId, String userId, Map<String, Object> data) {
        log.info("处理新增配送记录: deliveryId={}, userId={}", deliveryId, userId);
        
        // 这里可以添加具体的业务逻辑，比如：
        // 1. 发送配送通知
        // 2. 更新用户配送状态缓存
        // 3. 触发配送流程
        // 4. 记录配送日志
    }
    
    /**
     * 处理更新配送记录
     */
    private void handleUpdateDelivery(String deliveryId, String userId, String status, Map<String, Object> data) {
        log.info("处理更新配送记录: deliveryId={}, userId={}, status={}", deliveryId, userId, status);
        
        // 根据配送状态执行不同的业务逻辑
        if ("DELIVERED".equals(status)) {
            // 配送完成的处理逻辑
            log.info("配送完成: deliveryId={}", deliveryId);
        } else if ("CANCELLED".equals(status)) {
            // 配送取消的处理逻辑
            log.info("配送取消: deliveryId={}", deliveryId);
        }
    }
    
    /**
     * 处理删除配送记录
     */
    private void handleDeleteDelivery(String deliveryId, String userId, Map<String, Object> data) {
        log.info("处理删除配送记录: deliveryId={}, userId={}", deliveryId, userId);
        
        // 删除相关的缓存和数据
    }
    
    @Override
    public String getDatabase() {
        return "sharding_order_db"; // 监听分库分表的数据库
    }
    
    @Override
    public String getTable() {
        return null; // 在onDataChange方法中过滤user_delivery_开头的表
    }
    
    @Override
    public String[] getEventTypes() {
        return new String[]{"INSERT", "UPDATE", "DELETE"}; // 监听所有类型的事件
    }
}